package com.itic.mall.mobile.pay;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alipay.api.domain.GoodsDetail;
import com.alipay.api.domain.OrderItem;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.type.CouponState;
import com.itic.appbase.framework.type.CouponType;
import com.itic.appbase.framework.type.OperateType;
import com.itic.appbase.framework.type.OrderType;
import com.itic.appbase.framework.type.PreIncomeChannel;
import com.itic.appbase.framework.type.PreIncomeType;
import com.itic.appbase.framework.type.PreType;
import com.itic.appbase.framework.type.TaxCompany;
import com.itic.appbase.framework.type.UserType;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.mobile.goods.vo.GoodsDetailVo;
import com.itic.mall.mobile.orders.OrderDetailVo;
import com.itic.mall.mobile.orders.PayOrderVo;
import com.itic.mall.mobile.users.address.UsersAddrVo;
import com.itic.mall.system.goods.goodssku.service.GoodsSkuService;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpu;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample;
import com.itic.mall.system.goods.goodsspu.service.GoodsSpuService;
import com.itic.mall.system.orders.detail.persistence.model.OrdersDetail;
import com.itic.mall.system.orders.item.persistence.model.OrdersItem;
import com.itic.mall.system.orders.item.service.OrdersItemService;
import com.itic.mall.system.pay.userlog.persistence.model.PayUserlog;
import com.itic.mall.system.project.score.service.ProjectScoreService;
import com.itic.mall.system.users.address.persistence.model.Usersaddress;
import com.itic.mall.system.users.address.persistence.model.UsersaddressExample;
import com.itic.mall.system.users.address.service.UsersaddressService;
import com.itic.mall.system.users.pointslog.persistence.model.UsersPointslog;
import com.itic.mall.system.users.pointslog.persistence.model.UsersPointslogExample;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.sun.star.uno.RuntimeException;
import com.itic.mall.system.users.shoppingcart.service.UsersShoppingCartService;
import com.itic.mall.system.users.shoppingcartitem.service.UsersShoppingCartItemService;
import com.itic.mall.system.users.usercoupon.persistence.model.UsersCoupon;
import com.itic.mall.system.users.usercoupon.service.UsersCouponService;
import com.itic.mall.system.users.shoppingcartitem.persistence.model.UsersShoppingCartItem;
import com.itic.mall.system.users.shoppingcartitem.persistence.model.UsersShoppingCartItemExample;
import com.itic.mall.system.users.shoppingcart.persistence.model.UsersShoppingCartExample;
import com.itic.mall.system.users.shoppingcart.persistence.model.UsersShoppingCart;

@Controller
@RequestMapping(value = "/mobile/userspay")
public class UsersPayInterface extends BaseMobileInterface {

	@Autowired
	private UsersaddressService usersaddressService;
	@Autowired
	private UsersShoppingCartService usersShoppingCartService;
	@Autowired
	private UsersShoppingCartItemService usersShoppingCartItemService;
	@Autowired
	private GoodsSpuService goodsSpuService;
	@Autowired
	private GoodsSkuService goodsSkuService;
	@Autowired
	private OrdersItemService ordersItemService;
	@Autowired
	private UsersCouponService usersCouponService;
	@Autowired
	private ProjectScoreService projectScoreService;

	/**
	 * 根据用户ID获取默认地址
	 * 
	 * @param userId
	 * @return
	 */
	public UsersAddrVo getAddrByUserId(String token, String appId) {
		UsersAddrVo Vo = new UsersAddrVo();
		try {
			UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
			if (usersMall != null) {
				String userId = usersMall.getId();
				if (StringHelper.isNotBlank(userId)) {
					UsersaddressExample example = new UsersaddressExample();
					com.itic.mall.system.users.address.persistence.model.UsersaddressExample.Criteria criteria = example
							.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andUserIdEqualTo(userId);
					criteria.andIsDefaultAddressEqualTo(DBConst.TRUE);// 默认地址
					List<Usersaddress> list = usersaddressService.list(example);
					if (list.size() > 0) {
						Vo.setCity(list.get(0).getCity());
						Vo.setDetail(list.get(0).getDetail());
						Vo.setReceiverName(list.get(0).getReceiverName());
						Vo.setReceiverPhone(list.get(0).getReceiverPhone());
						Vo.setId(list.get(0).getId());
					}
				}
			}
		} catch (Exception e) {
			logException("OrdersdetailInterface", "getAddrByUserId", e.toString(), "根据用户ID获取默认地址", e);
		}
		return Vo;
	}

	/**
	 * 根据地址ID获取地址
	 * 
	 * @param addrId
	 * @return
	 */
	public UsersAddrVo getAddrById(String addrId) {
		UsersAddrVo usersAddrVo = new UsersAddrVo();
		if (StringHelper.isNotBlank(addrId)) {
			UsersaddressExample example = new UsersaddressExample();
			com.itic.mall.system.users.address.persistence.model.UsersaddressExample.Criteria criteria = example
					.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andIdEqualTo(addrId);
			List<Usersaddress> list = usersaddressService.list(example);
			if (list.size() > 0) {
				usersAddrVo.setId(addrId);
				usersAddrVo.setDetail(list.get(0).getDetail());
				usersAddrVo.setReceiverName(list.get(0).getReceiverName());
				usersAddrVo.setReceiverPhone(list.get(0).getReceiverPhone());
			}
		}
		return usersAddrVo;
	}
	/**
	 * 购物车中商品下订单后删除
	 * @param userId
	 * @param skuId
	 * @param count
	 * @return
	 */
	public void delCart(String userId,String skuId,int count){
		String result = FAIL;
		try{
			UsersShoppingCartItemExample example = new UsersShoppingCartItemExample();
			com.itic.mall.system.users.shoppingcartitem.persistence.model.UsersShoppingCartItemExample.Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andGoodsIdEqualTo(skuId);
			criteria.andUserIdEqualTo(userId);
			criteria.andCountEqualTo(count);
			List<UsersShoppingCartItem> list = usersShoppingCartItemService.list(example);
			if(list.size()>0){
				String cartId = list.get(0).getCartId();
				result = usersShoppingCartItemService.delete(list.get(0));
				if(SUCCESS.equals(result)){
					UsersShoppingCartExample examplec = new UsersShoppingCartExample();
					com.itic.mall.system.users.shoppingcart.persistence.model.UsersShoppingCartExample.Criteria criteriac = examplec.createCriteria();
					criteriac.andIsEffectiveEqualTo(DBConst.TRUE);
					criteriac.andUserIdEqualTo(userId);
					criteriac.andCartIdEqualTo(cartId);
					List<UsersShoppingCart> listc = usersShoppingCartService.list(examplec);
					if(listc.size()>0){
						result = usersShoppingCartService.delete(listc.get(0));
					}
				}
			}
		}catch(Exception e){
			logException("delCart", "delCart", e.toString(), "购物车中商品下订单后删除", e);
		}
	}
	/**
	 * 预支付接口
	 * 
	 * @param request
	 * @param response
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value = "/paydetail")
	@ResponseBody
	public Map<String, Object> paydetail(HttpServletRequest request, HttpServletResponse response, String token,
			String appId, String skuIdCounts) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringUtils.isNoneBlank(token,appId,skuIdCounts)) {
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if(usersMall!=null) {
					double totalAmount = 0;
					double compareAmount =0;
					PayDetailVo payDetailVo = new PayDetailVo();
					//获取收货地址
 					UsersAddrVo usersAddrVo = getAddrByUserId(token, appId);
					List<GoodsDetailVo> listgoods = new ArrayList<GoodsDetailVo>();
					//解析skuIdCounts 为map
					Map<String, String> skuMap = this.parseSkuIdCounts(skuIdCounts);
					StringBuffer skuIds = new StringBuffer();
					for(String skuId:skuMap.keySet()) {
						GoodsSpu goodsSpu = this.goodsSpuService.getBySku(skuId);
						skuIds.append(skuId);
						int count = Integer.parseInt(skuMap.get(skuId));
						GoodsDetailVo goodsDetailVo = this.goodsSkuService.getSkuDetailBySkuId(skuId, count);
						goodsDetailVo.setStoreId(usersMall.getYunId());
						Map<String, Object> skuPriceMap = this.ordersItemService.calPrice(usersMall.getId(),goodsSpu.getIsGoodsCoupon(),skuId,count);
						totalAmount += (double) skuPriceMap.get(skuId);
						if(goodsSpu.getIsSysCoupon()!=null && "1".equals(goodsSpu.getIsSysCoupon()))
							compareAmount+=goodsDetailVo.getPrice()*goodsDetailVo.getCount();
						List<UsersCoupon> usersCoupons = this.usersCouponService.findCouponListByUserIdAndSpuId(usersMall.getId(), goodsSpu.getId());
						if(usersCoupons.isEmpty())
							goodsDetailVo.setIsRevice("0");
						else
							goodsDetailVo.setIsRevice("1");
						listgoods.add(goodsDetailVo);
					}
					payDetailVo.setIsUsePoint("0");
					payDetailVo.setIsUseSysCoupon("0");
					for(GoodsDetailVo goodsDetailVo:listgoods){
						if("1".equals(goodsDetailVo.getIsUsePoint()))
							payDetailVo.setIsUsePoint("1");
						else
							payDetailVo.setIsUsePoint("0");
						if("1".equals(goodsDetailVo.getIsUseSysCoupon()))
							payDetailVo.setIsUseSysCoupon("1");
						else
							payDetailVo.setIsUseSysCoupon("0");
					}
					payDetailVo.setSkuIds(skuIds.toString());
					payDetailVo.setUsersAddrVo(usersAddrVo);
					payDetailVo.setTotalAmount(totalAmount);
					payDetailVo.setCompareAmount(compareAmount);
					payDetailVo.setGoodsList(listgoods);
					//根据totalAmount 计算用户可使用多少惠金币
					Map<String, Double> score = this.projectScoreService.calUserScoreRatio(usersMall,compareAmount);
					payDetailVo.setPointsAmount(score.get("deduc"));
					payDetailVo.setPoints(score.get("use").intValue());
					//返回用户可使用的系统优惠券
					List<UsersCoupon> usersCoupons = this.usersCouponService.getUsersCouponByUserId(usersMall.getId(),CouponState.sys,"0");
					List<Map<String, Object>> couponList = new ArrayList<>();
					for(UsersCoupon coupon : usersCoupons) {
						Map<String, Object>  couponMap = new HashMap<>();
						couponMap.put("id", coupon.getId());
						couponMap.put("name", coupon.getCouponName());
						couponMap.put("startTime",DateHelper.formatDate(coupon.getStartTime()));
						couponMap.put("endTime",DateHelper.formatDate(coupon.getEndTime()));
						couponMap.put("useCond", coupon.getUseCond());
						couponMap.put("amount", coupon.getAmount());
						couponMap.put("type", coupon.getType());
						couponList.add(couponMap);
					}
					payDetailVo.setCouponList(couponList);
					resultMap.put(DATA, payDetailVo);
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
				}else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "paydetail", e.toString(), "支付详情页面接口", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
		
	private double calOrderDetailActualPay(List<OrdersItem> ordersItems) {
		double actualPay = 0;
		for(OrdersItem ordersItem : ordersItems)
			actualPay +=ordersItem.getActualPay();
		return actualPay;
	}
	
	
	/**
	 * 提交订单
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param goodsId
	 * @param cartIds
	 * @param counts
	 * @return
	 */
	@RequestMapping(value = "/submitOrder")
	@ResponseBody
	public Map<String, Object> submitOrder(HttpServletRequest request, HttpServletResponse response, String token,
			String appId,String orderNo, String skuIdCounts, String couponId,String isUsePoints,Integer point ,Double deducMoney, String id,Double expressFee,double actualMoney,String yunId,String buyMsg) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringUtils.isNotEmpty(orderNo)){
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
				resultMap.put(DATA, orderNo);
				resultMap.put(CODE, errorCode);
				resultMap.put(MSG, errorMsg);
				isCrrossDomain(response);
				return resultMap;
			}
			if(StringUtils.isNoneBlank(token,appId,skuIdCounts,isUsePoints,id)) {
				UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
				if(usersMall!=null) {
					Map<String, String> skuMap = this.parseSkuIdCounts(skuIdCounts);
					if(!skuMap.isEmpty()) {
						boolean flag = true;
						boolean skuFalg = true;
						for(String key:skuMap.keySet()) {
							GoodsSpu goodsSpu = this.goodsSpuService.getBySku(key);
							if(goodsSpu == null){
								resultMap.put(CODE, GOODS_NOT_EXIST_MSG);
								resultMap.put(MSG, GOODS_NOT_EXIST_MSG);
								isCrrossDomain(response);
								return resultMap;
							}
							//添加每个订单到order_detail
							int number =  Integer.parseInt(skuMap.get(key));

							int skuNumber = this.goodsSkuService.getTotalInventoryBySkuIdAndcount(key, number);

							if(skuNumber<=0) {
								skuFalg = false;
								break;
							}
							if(number <=0) {
								flag = false;
								break;
							}
						}
						if(skuFalg) {
							if(flag) {
								//添加orderItem
								orderNo = RandomOrderNumHelper.getOrderNumber();
								List<OrdersItem> ordersItems = this.ordersItemService.addOrderItem(skuMap, orderNo,usersMall.getYunId(),usersMall.getId());
								double sumAmount = 0;
								double sumPayCouponAmount =0;
								for(OrdersItem ordersItem : ordersItems) {
									sumAmount += ordersItem.getPrice();
									GoodsSpu goodsSpu = this.goodsSpuService.getBySku(ordersItem.getSkuId());
									if("1".equals(goodsSpu.getIsSysCoupon()))
										sumPayCouponAmount+=ordersItem.getActualPay();
								}
								if(sumPayCouponAmount>0 && StringUtils.isNotEmpty(couponId)) {
									UsersCoupon usersCoupon = this.usersCouponService.getUsersCouponByCouponId(couponId);
									double sumCouponMoney = 0;
									if(usersCoupon !=null) {
										sumCouponMoney+=usersCoupon.getAmount();
									}
									if("1".equals(isUsePoints))
										sumCouponMoney +=deducMoney==null?0:deducMoney;
									for(OrdersItem ordersItem : ordersItems) {
										GoodsSpu goodsSpu = this.goodsSpuService.getBySku(ordersItem.getSkuId());
										if("1".equals(goodsSpu.getIsSysCoupon())) {
											this.ordersItemService.calItemCouponMoney(ordersItem, sumCouponMoney, sumPayCouponAmount);
										}else 
											ordersItem.setCouponPrice(0D);
									}
								}
								for(OrdersItem ordersItem : ordersItems) 
									this.ordersItemService.add(ordersItem);
								/*if(StringUtils.isEmpty(yunId))
									yunId = usersMall.getYunId();*/
								String result = this.ordersDetailService.addOrderDetail(deducMoney,point,sumAmount, isUsePoints, usersMall.getUserNickName(), orderNo, expressFee, actualMoney,yunId, usersMall.getId(), id,couponId,buyMsg);
								if(StringUtils.isNotEmpty(couponId))
									this.usersCouponService.editUseUserCouponById(couponId);
								resultMap.put(DATA, orderNo);
								errorCode = SUCCESS_ERROR_CODE;
								errorMsg = SUCCESS_ERROR_MSG;
							}else {
								errorCode = NOT_SELECT_SKU_COUNT_CODE;
								errorMsg = NOT_SELECT_SKU_COUNT_MSG;
							}
						}else {
							errorCode = SKU_NUMBER_NOT_ENOUGH_CODE;
							errorMsg = SKU_NUMBER_NOT_ENOUGH_MSG;
						}
					}
				}else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "submitOrder", e.toString(), "提交订单", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

	/**
	 * 购物车到支付详情页面
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param goodsId
	 * @return
	 */
	@RequestMapping(value = "/shoppingcartpay")
	@ResponseBody
	public Map<String, Object> shoppingcartpay(HttpServletRequest request, HttpServletResponse response, String token,
			String appId, String cartIds) {
		// goodsId 不止一个 可能是多个拼接
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<GoodsDetailVo> listgoods = new ArrayList<GoodsDetailVo>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		double couponAmount = 0;
		String[] strArray = null;
		try {
			UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
			if (usersMall != null) {
				double totalAmount = 0;
				String userId = usersMall.getId();
				strArray = cartIds.split(",");
				CartPayVo cartPayVo = new CartPayVo();
				for (int i = 0; i < strArray.length; i++) {
					String cartId = strArray[i];
					// 根据购物车ID去取购物车项信息
					UsersShoppingCartItemExample example = new UsersShoppingCartItemExample();
					com.itic.mall.system.users.shoppingcartitem.persistence.model.UsersShoppingCartItemExample.Criteria criteria = example
							.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andCartIdEqualTo(cartId);
					criteria.andUserIdEqualTo(userId);
					List<UsersShoppingCartItem> list = usersShoppingCartItemService.list(example);
					if (list.size() > 0) {
						UsersShoppingCartItem usersShoppingCartItem = list.get(0);
						String goodsId = usersShoppingCartItem.getGoodsId();
						int count = usersShoppingCartItem.getCount();
						// 根据商品ID获取商品信息
						GoodsDetailVo goodsDetailVo = getGoodsDetailBySkuId(goodsId, count);
						totalAmount = totalAmount + goodsDetailVo.getPrice() * goodsDetailVo.getCount();
						listgoods.add(goodsDetailVo);
						// 根据商品ID获取红包券
						couponAmount = couponAmount + getCouponAmountByGoodsId(goodsId);
					}

				}
				cartPayVo.setCouponAmount(couponAmount);
				cartPayVo.setTotalAmount(totalAmount);
				cartPayVo.setGoodsList(listgoods);
				// 获取积分信息
				UsersPointslogExample example = new UsersPointslogExample();
				com.itic.mall.system.users.pointslog.persistence.model.UsersPointslogExample.Criteria criteria = example
						.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andUserIdEqualTo(userId);
				List<UsersPointslog> list = usersPointslogService.list(example);
				if (list.size() > 0) {
					cartPayVo.setPoints(list.get(0).getPoints());
					cartPayVo.setPointsAmount(list.get(0).getPointsAmount());
				}
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
				resultMap.put(DATA, cartPayVo);
			} else {
				errorCode = LOGIN_ERROR_CODE;
				errorMsg = LOGIN_ERROR_MSG;
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "shoppingcartpay", e.toString(), "购物车到支付详情页面", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
	}

	@RequestMapping(value = "/actualPay")
	@ResponseBody
	public Map<String, Object> actualPay(HttpServletRequest request, HttpServletResponse response, String isUsePoints,
			double pointsAmount, double totalAmount) {
		// goodsId 不止一个 可能是多个拼接
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			String pmoney = String.valueOf(pointsAmount);
			String money = String.valueOf(totalAmount);
			if (StringHelper.isNotBlank(isUsePoints) && money != "null") {
				if (isUsePoints.equals("1") && pmoney != "null") {
					totalAmount = totalAmount - pointsAmount;
				} else {

				}
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
				resultMap.put("totalAmount", totalAmount);
			}

		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "cartpayIsusePoints", e.toString(), "购物车到支付详情页面", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
	}

	/**
	 * 用户提现
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param receiverName
	 * @param city
	 * @param detail
	 * @param receiverPhone
	 * @param isdefault
	 * @return
	 */
	@RequestMapping(value = "/withdraw")
	@ResponseBody
	public Map<String, Object> add(HttpServletRequest request, HttpServletResponse response, String token, String appId,
			String receiverName, String city, String detail, String receiverPhone, String isdefault) {
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String result = FAIL;
		try {

		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("UsersaddressInterface", "withdraw", e.toString(), "用户提现", e);
		}
		return resultMap;
	}
	@RequestMapping(value = "/cal/profit")
	@ResponseBody
	public Map<String, Object> calUserProfit(HttpServletResponse response,String userId,String commission,String taxCompany,String orderNo,String preType,String channel,String skuId,String operateType,String preIncomeType){
		//throw new RuntimeException();
		Map<String, Object> resultMap = new HashMap<>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringUtils.isNoneBlank(userId,commission,orderNo,skuId) && taxCompany!=null && preType !=null && channel!=null && operateType!=null && preIncomeType!=null) {
				List<PayUserlog> payUserlogsPre = this.payUserlogService.getPreAmountByOrderNoAndSkuIdAndType(orderNo, skuId, PreType.pre);
				List<PayUserlog> payUserlogsActual = this.payUserlogService.getPreAmountByOrderNoAndSkuIdAndType(orderNo, skuId, PreType.actual);
				
				if(payUserlogsPre.isEmpty()&& payUserlogsActual.isEmpty()){
					TaxCompany compnat = TaxCompany.getTaxCompany(taxCompany);
					PreType type = PreType.getPreType(preType);
					PreIncomeChannel preIncomeChannel = PreIncomeChannel.getType(channel);
					OperateType operType = OperateType.add;
					if(OperateType.sub.toString().equals(operateType))
						operType = OperateType.sub;
					PreIncomeType incomeType = PreIncomeType.getType(preIncomeType);
					UsersMall usersMall = this.usersMallService.get(userId);
					String result = this.payUserlogService.addUserTeamPreProfit(usersMall, commission,compnat, orderNo,type, preIncomeChannel, skuId,operType,incomeType,1);
				}
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
			}else {
				errorCode = PARAM_ERROR_CODE;
				errorMsg = PARAM_ERROR_MSG;
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("UsersPayInterface", "calUserProfit", e.toString(), "计算佣金", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

}
